package cn.lyjuan.android.demofive.frame.tpl;


import cn.lyjuan.android.demofive.frame.realm.UserModel;
import cn.lyjuan.android.mylibrary.util.Logger;
import cn.lyjuan.base.util.ReflectUtils;
import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmModel;
import io.realm.RealmQuery;
import io.realm.RealmResults;

/**
 * Realm作数据源
 * Created by chad on 12/11/2017.
 */

public abstract class AbstractRealmDataSource<T extends RealmModel> implements IDataSource<RealmResults<T>>
{
    protected Realm realm;

    protected Class cls = ReflectUtils.getGenericityClass(AbstractRealmDataSource.class, 0);

    protected IFetchDataListener<RealmResults<T>> listener;


    public AbstractRealmDataSource(Realm realm)
    {
        this.realm = realm;
    }

    @Override
    public void fetchData(final boolean clear)
    {
        try
        {
            RealmQuery query = realm.where(UserModel.class);

            realmQuery(query);

            RealmResults<T> results = query.findAllAsync();

            results.addChangeListener(new RealmChangeListener<RealmResults<T>>()
            {
                @Override
                public void onChange(RealmResults<T> ts)
                {
                    if (null == ts) return;// 因为Realm查询集合不会为null

                    if (null != listener)// Realm只调用成功
                        listener.onFetchSucc(ts, clear);
                }
            });
        } catch (Exception e)
        {
            if (null != listener)
                listener.onFetchFail(1, null);

            Logger.e("TAG", "realm error", e);
        }
    }

    /**
     * 封装RealmQuery条件
     *
     * @param query
     */
    protected abstract void realmQuery(RealmQuery query);

    @Override
    public boolean isSucc(RealmResults<T> ts)
    {
        return true;// 始终返回true
    }

    @Override
    public void setFetchDataListener(IFetchDataListener<RealmResults<T>> listener)
    {
        if (null != this.listener)
            throw new IllegalStateException("fetchDataListener exists for " + this.listener.getClass().getName());

        this.listener = listener;
    }

    public Realm getRealm()
    {
        return realm;
    }

    public void setRealm(Realm realm)
    {
        this.realm = realm;
    }

    public Class getCls()
    {
        return cls;
    }

    public void setCls(Class cls)
    {
        this.cls = cls;
    }

    public IFetchDataListener<RealmResults<T>> getListener()
    {
        return listener;
    }

    public void setListener(IFetchDataListener<RealmResults<T>> listener)
    {
        this.listener = listener;
    }
}
